import React, { useEffect, useState, useMemo } from 'react';
import { queryOrderDetail, queryReceiveOrderStatus, queryServeCall, queryOrderFinish, queryUseIntegral } from '@/services/order';
import { history, useDispatch, useSelector, Link } from 'umi';
import Header from '@/components/Header/Header';
import useDebounceFn from '@/utils/useDebounceFn';
import { isEmpty, storeOptionListMap, getUmePic } from '@/utils/common';
import PaymentModal from './components/PaymentModal';
import { Picture, Price, SlideBox, AffixBottom, AsyncLoading, Modal, Message } from '@/design';
import moment from 'moment';
import SelectCoupon from './components/SelectCoupon';
import { umeAppPath } from '@/config'
import styles from './orderDetail.less';

function POrderDetail(props: any) {
  let unmount = false;
  const dispatch = useDispatch();
  const [orderInfo, setOrderInfo] = useState<any>({});
  const [receiveOrderStatusInfo, setReceiveOrderStatusInfo] = useState<any>();
  const { codeDetail, storeOptionList } = useSelector((state: any) => state.store);
  const { currentstore } = useSelector((state: any) => state.currentstore);
  const [moreProduct, setMoreProduct] = useState<boolean>(false); // 商品列表开关
  const [paymentVisiable, setPaymentVisiable] = useState<boolean>(false);
  const { orderNo = undefined } = props.location.query;
  const diningWayTypes = new Map([['diningroom', '堂食'], ['takeout', '外帶'], ['togoBespeak', '預約外帶']]);
  const orderStatusTypes = new Map([['unconfirm', '等待確認訂單'], ['nopay', '未支付'], ['invalid', '已取消'], ['confirmed', '已確認'], ['blankout', '已作廢'], ['payed', '已支付']]);
  const userInfo = localStorage.getItem('userInfo');
  const [selectCouponVisiable, setSelectCouponVisiable] = useState<boolean>(false);
  let timed: any = undefined;
  useEffect(() => {
    fetchOrderDetail();
    return () => {
      unmount = true;
    }
  }, []);

  useEffect(() => {
    if (isEmpty(receiveOrderStatusInfo)) {
      fetchReceiveOrderStatus();
    }
    return () => {
      unmount = true;
    }
  }, [orderInfo]);

  // useEffect(() => {
  //   fetchServeCall();
  // }, [canClickServe])

  // useEffect(()=>{
  //   fetchStoreDetail();
  // }, [storeDetail]);

  // useEffect(()=>{
  //   fetchCodeDetail()
  // }, []);

  const fetchReceiveOrderStatus = async () => {//返回是012的時候終止
    // isFirstEat ？ data 0
    if (!isEmpty(orderInfo) && orderInfo.isFirstEat && orderInfo.orderStatus !== 'payed') {
      let res = await queryReceiveOrderStatus(orderInfo.orderId);
      if (res.data === 1 || res.data === 2 || res.data === 0) {
        setReceiveOrderStatusInfo(res.data);
        clearInterval(timed);
      } else {
        timed = setInterval(async () => {
          fetchReceiveOrderStatus();
        }, 5000);
        return () => {
          clearInterval(timed);
        }
      }
    } else if (isPayed()) {
      let res = await queryReceiveOrderStatus(orderInfo.orderId);
      if (res.data === 1 || res.data === 2 || res.data === 0) {
        setReceiveOrderStatusInfo(res.data);
        clearInterval(timed);
      }
    }
  }

  const fetchOrderDetail = async () => {
    if (isEmpty(orderNo)) {
      return;
    };
    let result = await queryOrderDetail({ id: orderNo, isReturnUmeIntegral: '1' });
    if (unmount || !result) return;
    setOrderInfo(result.data);
  }

  const isTakeout = () => {//是否是預約外帶和到點外帶
    const { diningWay } = orderInfo;
    return diningWay === 'togoBespeak' || diningWay === 'togo' || diningWay === 'togoCash';
  }

  const isPayed = () => {
    const { orderStatus } = orderInfo;
    return orderStatus === 'payed';
  }

  /* 隐藏/开启  商品列表 */
  const handleProductChange = () => {
    setMoreProduct(!moreProduct);
  };

  /* 所选的菜品规格 */
  const chooseSpecs = (tasteList: any) => {
    let str: any = [];
    tasteList.forEach((o: any) => {
      str.push(`${o.tasteName}`)
    })
    return str.join('/')
  }

  // 計算所選的規格的總價格（所選規格 + 菜品價格）
  const chooseSpecPrice = (arr: any, productPrice: number) => arr.reduce((acc: any, after: any) => {
    return acc + after.price;
  }, productPrice);


  /* 渲染商品 */
  const RenderProduct = ({ item, isReturned }: any) => {
    // console.log(item)
    const itemStatusType = new Map([['returned', '已退菜'], ['confirmed', '已確認'], ['unconfirmed', '未確認'], ['payed', '已支付']]);

    return <div className={styles.product_item}>
      <Picture className={styles.pic} src={getUmePic(item.productIcon)} />
      <div className={styles.info}>
        {/* 商品信息 */}
        <div className={styles.goods_info}>
          <div>
            <h3 className={styles.name}>
              <i>{item.productName}</i>
              <i className={styles.detailStatus}>
                {!isReturned ? item.detailStatus === 'confirmed' ? '已確認' : '未確認' : itemStatusType.get(item.itemStatus)}
              </i>
            </h3>
            <div className={styles.price}>X {item.productQuantity}</div>
          </div>
          {/* 规格属性 */}
          {item.tasteList.length > 0 && <p className={styles.spec}>
            <span>
              <Price price={chooseSpecPrice(item.tasteList, item.productPrice)} />
              {/* <Price price={item.productPrice} /> */}
            </span>
            {!isEmpty(item.tasteList) && <span className={styles.spec_num}>
              {chooseSpecs(item.tasteList)}
              {/* {item.productQuantity} */}
            </span>}
          </p>}
        </div>
        {/* 價格信息 */}
        {/* <div className={styles.price_info}>
          <Price price={item.productPrice} />
        </div> */}
      </div>
    </div>
  }

  // 订单相关备注
  const renderOrderDesc = () => {
    return (<div className={styles.remark_wrap}>
      <div className={`${styles.remark_item}`}>
        <label>下單時間:</label>
        <strong>{orderInfo.formatCreateTime}</strong>
      </div>
      <div className={`${styles.remark_item}`}>
        <label>訂單編號:</label>
        <strong>{orderInfo.orderId}</strong>
      </div>
      <div className={`${styles.remark_item}`}>
        <label>就餐方式:</label>
        <strong>{diningWayTypes.get(orderInfo.diningWay)}</strong>
      </div>
      <div className={`${styles.remark_item}`}>
        <label>備註:</label>
        <strong>{orderInfo.orderRemark}</strong>
      </div>
      {isTakeout() && <>
        {orderInfo.diningWay === 'togoBespeak' || orderInfo.diningWay === 'togoCash' && <div className={`${styles.remark_item}`}>
          <label>預約時間:</label>
          <strong>{moment(orderInfo.bespeakStartTime).format("YYYY-MM-DD HH:mm")}</strong>
        </div>}

        <div className={`${styles.remark_item}`}>
          <label>客戶姓名:</label>
          <strong>{orderInfo.comsumerName}</strong>
        </div>
        <div className={`${styles.remark_item}`}>
          <label>客戶電話:</label>
          <strong>{orderInfo.comsumerPhone}</strong>
        </div>
      </>}

    </div>)
  }

  //支付按钮
  const renderPayBtn = () => {
    return (orderInfo?.orderStatus !== 'payed' ? <div className={styles.pay_wrap}>
      <div className={styles.pay_hidden}></div>
      <AffixBottom className={styles.pay_main}>
        {<strong className={styles.real_amount}><Price price={orderInfo.orderAmount} /></strong>}
        <button type="button" className={styles.pay_button} onClick={handlePay}>立即支付</button>
      </AffixBottom>
    </div> : null)
  }

  //订单价格相关
  const renderPirceDesc = () => {
    return (!isEmpty(orderInfo.orderTotalSourceAmount) && <div className={styles.order_payment}>

      {<>
        {orderInfo.serveAmount > 0 && <div className={`${styles.info_item}`}>
          <label>服務費</label>
          <strong><Price price={orderInfo.serveAmount} /></strong>
          {/* <span className={styles.under}>- <Price price={12} /></span> */}
        </div>
        }
        {orderInfo.seatAmount > 0 && <div className={`${styles.info_item}`}>
          <label>餐位費</label>
          <strong><Price price={orderInfo.seatAmount} /></strong>
        </div>
        }
        <div className={`${styles.info_item}`}>
          <label>小計</label>
          <strong><Price price={orderInfo.orderTotalSourceAmount} /></strong>
        </div>
        {orderInfo.memberDiscountAmount > 0 && <div className={`${styles.info_item}`}>
          <label>會員折扣</label>
          <strong>
            <span className={styles.under}>- <Price price={orderInfo.memberDiscountAmount} /></span>
          </strong>
        </div>
        }
        {orderInfo.integralDeductionCash > 0 && <div className={`${styles.info_item}`}>
          <label>積分折扣：</label>
          <strong>
            <span className={styles.under}>- <Price price={orderInfo.integralDeductionCash} /></span>
          </strong>
        </div>
        }
        {orderInfo.couponAmount > 0 && <div className={`${styles.info_item}`}>
          <label>優惠券</label>
          <strong>
            <span className={styles.under}>- <Price price={orderInfo.couponAmount} /></span>
          </strong>
        </div>
        }
      </>}

      {<div className={styles.need_pay}>
        <i>總計</i>
        <Price price={orderInfo.orderAmount} />
      </div>}
    </div>)
  }

  //訂單已支付 顯示狀態
  const renderAfterPayDesc = () => {
    const types = new Map([[0, '未接單'], [1, '接單成功'], [2, '接單失敗，請聯繫服務員']]);
    const descTypes = new Map([[0, '很抱歉，具體原因聯繫服務員'], [1, '廚師正在為您盡心準備中'], [2, '很抱歉，具體原因聯繫服務員']]);
    const classNameTypes = new Map([[0, 'order_status_fail'], [1, 'order_status_success'], [2, 'order_status_fail']]);

    if (!isEmpty(receiveOrderStatusInfo)) {
      return (<div className={`${receiveOrderStatusInfo !== 2 ? styles.has_bg : ''} ${styles.orderstatus_wrap}`}>
        <span className={`${styles.order_status_icon} ${classNameTypes.get(receiveOrderStatusInfo)}`}></span>
        <span>
          <i>{types.get(receiveOrderStatusInfo)}</i>
          <i>{descTypes.get(receiveOrderStatusInfo)}</i>
        </span>
      </div>)
    }
    return <></>
  }

  // 支付
  const handlePay = () => {
    // 0元
    if (orderInfo.orderAmount === 0) {
      fetchOrderFinish();
      return;
    }
    if (storeOptionListMap(storeOptionList).get('is_first_eat') === '1') {
      if (orderInfo.orderStatus === 'unconfirm') {//是否是先吃 需要服務員確認
        return Modal.alert({
          content: '訂單已提交，等待服務員確認',
        })
      }
      setPaymentVisiable(true);
    } else {
      setPaymentVisiable(true);
    }
  }

  //0元標記已支付
  const fetchOrderFinish = async () => {
    let result = await queryOrderFinish({ orderId: orderInfo.orderId, isReturnDetail: 1 })
    if (!result || !result.data) return false;
    if (result.data.orderStatus === 'payed') {
      Message.success('支付成功！');
      setOrderInfo(result.data);
    }
  }

  const linkToLogin = () => {
    history.push('/line')
  }

  //userInfo
  const renderRemindLogin = () => {
    return (
      <>
        {isEmpty(userInfo) ? <div className={styles.login_remind_wrap}>
          <div>
            <span className={styles.avatar}></span>
            <span>
              <i>註冊會員，領新手禮包</i>
              <i>立送20ume積分，支付最多可抵<Price price={123} /></i>
            </span>
          </div>
          <button onClick={linkToLogin}>註冊/登入</button>
        </div> : <div className={styles.member_wrap}>
            <div>
              <i></i>
              <span>{orderInfo && orderInfo['member'] && orderInfo['member'].memberGradeName}</span>
            </div>
            <button onClick={() => setSelectCouponVisiable(true)}>{orderInfo.couponAmount > 0 ? <span><i>-</i><Price price={orderInfo.couponAmount} /></span> : '選擇優惠券'} <i className={styles.d_more}></i></button>
          </div>}
      </>
    )
  }

  // 提醒服務
  const renderServe = () => {
    return <div className={styles.table_code_wrap}>
      <div className={styles.table_code_info}>
        <div>
          <span className={styles.braName}><i></i>{currentstore?.braName}</span>
          {!isTakeout() && <button>呼叫</button>}
        </div>
        <div>
          <span>桌台號:{codeDetail?.tableCode}</span>
          <span>{isTakeout() && !isEmpty(orderInfo.orderSerialNo) ? `取單序號: ${orderInfo.orderSerialNo}` : <i className={styles.tag}>{orderStatusTypes.get(orderInfo.orderStatus)}</i>}</span>
        </div>
      </div>
      {!isTakeout() && <div className={styles.btns}>
        <button onClick={() => fetchServeCall()}><span className={styles.to_order_icon}></span>提醒上菜</button>
        {orderInfo.orderStatus !== 'payed' && <button><span className={styles.notice_icon}></span>繼續點餐</button>}
      </div>}
    </div>
  }

  // 呼叫業務
  const { run: fetchServeCall } = useDebounceFn(async () => {
    if (isEmpty(orderInfo)) {
      return Message.error('訂單號為空')
    }
    const { orderId } = orderInfo;
    const token = localStorage.getItem('TOKEN');
    let param: any = {
      orderId: orderId,
      serveType: '3', //1：现金支付；2：订单服务；0呼叫服务员, 3 提醒上菜
      tableCode: codeDetail.tableCode,
      userId: token //當前的token
    };

    let res = await queryServeCall(param);
    if (res.code === 200) {
      Message.success('呼叫成功')
    }
  }, 1000);

  // 刷新數據
  const onFresh = (orderInfo: any) => {
    if (!isEmpty(orderInfo)) {
      setOrderInfo(orderInfo);
    }
  }

  //linkToGetCoupon 
  const linkToGetCoupon = () => {
    // setSelectCouponVisiable(false)
    history.push('/getCoupon')
  }

  //计算有多少件菜品
  const countOccurrences = (arr: any) => arr.reduce((a: any, v: any) => (a + v.productQuantity), 0);

  // 設置積分抵現
  // if(value && !/^[0-9]+$/.test()) return Message.error('請輸入正確的積分數量');
  const handleSetIntegral = () => {
    const { maxIntegralDeductionQuantity } = orderInfo;
    return Modal.prompt({
      title: '使用積分抵扣',
      content: `本訂單最多可折抵NT$${maxIntegralDeductionQuantity}`,
      onConfirm: (value) => new Promise<any>(async (resolve) => {
        if (value && !/^[0-9]+$/.test(value)) return Message.error('請輸入正確的積分數量');
        if (isEmpty(value)) return Message.error('請輸入要抵扣積分數量');
        if (Number(value) > maxIntegralDeductionQuantity) return Message.error(`訂單最大能夠抵扣${maxIntegralDeductionQuantity}積分`);
        let result:any = await fetchUseIntegral(Number(value));
        if (!result || !result.data) { resolve(false); return false; }
        setOrderInfo(result.data);
        resolve(true);
      })
    })
  }

  const fetchUseIntegral = async (value: number) => {
    if (isEmpty(userInfo)) return;
    const { userId = '' } = JSON.parse(userInfo || '{}');

    let params = {
      orderId: orderInfo.orderId,
      userId,
      deductionIntegralQuantity: value
    }
    let loading =  Message.loading('訂單更新中')
    let res = await queryUseIntegral(params);
    loading.hide();
    return res;
  }

  // 下載ume
  const handleToDown = () => {
    (window as any).location.href = umeAppPath
  }

  // ume積分抵現
  const renderUmeIntegral = () => {
    return <div className={styles.integral_wrap}>
      <div className={styles.integral_picker}>
        <label>ume積分折抵</label>
        <div onClick={handleSetIntegral}>
          <span className={styles.integral_number}>
            請填寫
          </span>
        </div>
      </div>
      <div className={styles.integral_info}>
        <span>賬戶餘額：{orderInfo.userUmeIntegralQuantity}積分</span>
        <span>1ume積分=NT${orderInfo.integraDeductionProportion}</span>
      </div>
    </div>
  }

  // 下載ume
  const renderDownUmeIntegral = () => {
    return <div className={styles.integral_wrap}>
      <div className={styles.integral_picker}>
        <label>下載umeApp,積分可折抵</label>
        <div>
          <span className={styles.integral_number} onClick={handleToDown}>
            立即下載
          </span>
        </div>
      </div>
      <div className={styles.integral_info}>
        <span>賬戶餘額：{orderInfo.userUmeIntegralQuantity}積分</span>
        <span>本訂單最多可折抵 <Price price={orderInfo.maxIntegralDeductionQuantity}></Price></span>
      </div>
    </div>
  }

  // coupon modal sure
  const onClickSure = () => {
    setSelectCouponVisiable(false)
  }

  // 退菜列表
  const returnedList = useMemo(() => {
    if (isEmpty(orderInfo.orderItemList)) return [];
    return orderInfo.orderItemList.filter((cur: any) => cur.detailStatus === 'returned');
  }, [orderInfo.orderItemList]);

  // 正常列表
  const orderItemlist = useMemo(() => {
    if (isEmpty(orderInfo.orderItemList)) return [];
    return orderInfo.orderItemList.filter((cur: any) => cur.detailStatus !== 'returned');
  }, [orderInfo.orderItemList]);

  return !isEmpty(orderInfo) ? <>
    <div className={styles.orderdetail_wrap}>
      <Header hasBack title={'訂單詳情'}></Header>
      {/* 桌號信息 - 呼叫- 提醒上菜 */}
      {renderServe()}
      {/*支付後的訂單描述  */}
      {orderInfo.orderStatus === 'payed' && renderAfterPayDesc()}
      {/* 註冊會員 */}
      {!isPayed() && renderRemindLogin()}
      {/* 積分抵扣 */}
      {!isPayed() && renderUmeIntegral()}
      {/* 下載ume */}
      {!isPayed() && renderDownUmeIntegral()}
      {/* 正常商品信息 */}
      <div className={styles.order_products}>
        <h2 className={styles.title}>已點菜品共{countOccurrences(orderItemlist)}份</h2>
        {orderItemlist.length > 2
          ? orderItemlist.slice(0, 2).map((item: any) => <RenderProduct key={`${item.productId}_${item.index}`} item={item} />)
          : orderItemlist.map((item: any) => <RenderProduct key={`${item.productId}_${item.index}`} item={item} />)
        }
        {!isEmpty(orderItemlist) && <div className={styles.content}>
          {orderItemlist.length > 2 && <>
            <SlideBox isShow={moreProduct}>
              {orderItemlist.slice(2).map((item: any, index: number) => <RenderProduct key={`${item.productId}_${index}`} item={item} isReturned={false} />)}
            </SlideBox>
            <div className={styles.hideControl} onClick={handleProductChange}>
              <span>{moreProduct ? '收起' : `共 ${orderItemlist.length} 件`}</span>
              <i className={moreProduct ? styles.active : ''}></i>
            </div>
          </>}
        </div>}
      </div>

      {/* 已失效 */}
      {!isEmpty(returnedList) && <div className={`${styles.cancel} ${styles.order_products}`}>
        <h2 className={styles.title}>已失效菜品共{countOccurrences(returnedList)}份</h2>
        {returnedList.length > 2
          ? returnedList.slice(0, 2).map((item: any) => <RenderProduct key={`${item.productId}_${item.index}`} item={item} isReturned={true} />)
          : returnedList.map((item: any) => <RenderProduct key={`${item.productId}_${item.index}`} item={item} />)
        }
        {!isEmpty(returnedList) && <div className={styles.content}>
          {returnedList > 2 ? <>
            <SlideBox isShow={moreProduct}>
              {returnedList.slice(2).map((item: any, index: number) => <RenderProduct key={`${item.productId}_${index}`} item={item} />)}
            </SlideBox>
            <div className={styles.hideControl} onClick={handleProductChange}>
              <span>{moreProduct ? '收起' : `共 ${returnedList.length} 件`}</span>
              <i className={moreProduct ? styles.active : ''}></i>
            </div>
          </> : null}
        </div>}
      </div>}
      {/* 價格 */}
      {renderPirceDesc()}
      {/*備註相關  */}
      {renderOrderDesc()}
      {/* 支付按钮 */}
      {renderPayBtn()}
      <SelectCoupon selectCouponVisiable={selectCouponVisiable} orderAmount={orderInfo.joinDiscountProductAmount} orderNo={orderInfo.orderId} onClose={() => setSelectCouponVisiable(false)} onFresh={onFresh} orderItemList={orderInfo.orderItemList} onLink={linkToGetCoupon} btnName={'取消'} closeText='繼續領券' isPayed={isPayed()} onClickSure={onClickSure} myCouponId={orderInfo.myCouponId} />
    </div>
    <PaymentModal modalVisiable={paymentVisiable} onClose={() => setPaymentVisiable(false)} orderNo={orderNo} payAmount={orderInfo.orderAmount} orderStatus={orderInfo?.orderStatus} orderId={orderInfo.orderId} />
  </> : <AsyncLoading />
}
export default POrderDetail